<template>
  <div class="contain">
    <div  v-if="searchData.length!=0" class="seach-flied" :style="{height:flod? '140px':'80px'}">
      <div class="serch-contain">
        <mySeach id="refSearch" class="serch-item" @doClear="doClear" @doSearch="doSearch"
          v-for="(i,index) in searchData" :key="'seach' +index" :index="index" :option="i" :searchData="searchData">
        </mySeach>
      </div>
      <a-button type="text" class="fold-btn" @click="handleFold" v-if="searchData.length > 5">
        <span v-show="!flod">展开
          <down-outlined :style="{fontSize:'12px'}" />
        </span>
        <span v-show="flod">收起
          <up-outlined :style="{fontSize:'12px'}" />
        </span>
      </a-button>
    </div>
    <div class="table-box">
      <div class="slot-box">
      <div style="font-size:16px"><slot name="title" ></slot></div>
      <div><slot name="oprate"></slot></div>
      </div>
      <a-table size="small" :loading="loading" :columns="columns" :data-source="tableData" :pagination="false"
        @change="onChange">
        <template #bodyCell="{ column, record }">
          <myRender v-if="column.renderDom" :render="column.renderDom" :column="column" :row="record" />
        </template>
      </a-table>
      <div class="pagination-box">
        <a-pagination :current="current" :page-size="pageSize" :page-size-options="pageSizeOptions" :total="total"
          show-size-changer show-quick-jumper @change="onShowChange">
          <template #buildOptionText="props">
            <span v-if="props.value !== '150'" style="height: 32px;">{{ props.value }}条/页</span>
            <span v-else>全部</span>
          </template>
        </a-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { message } from "ant-design-vue";
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue';
import myRender from "./myRender.js";
import mySeach from "./mySearch.js";
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  defineProps,
  watch,
  onUnmounted
} from "vue";


const onChange = (pagination, filters, sorter)=>{
  // console.log(pagination, filters, sorter);
  // let data = [pagination, filters, sorter]
  // emit('change',data)
}
// 数据初始化
const props = defineProps({
  renderTable: {
    type: Function,
    require: true,
    default: ()=>{},
  },
  columns: {
    type: Array,
    require: true,
    default: [],
  },
  isRefrensh: {
    type: Number,
    default: 0,
  },
  searchData: {
    type: Array,
    default: [],
  },
  pageData: {
    type: Object,
    require: true,
    default: {},
  },
});

// 表格逻辑
const isfrensh = ref(0);
let reqDataArr = [];

const setPagedata = () => {
  let arr = []
  for (let key in props.pageData) {
    arr.push({ [key]: props.pageData[key] });
  }
  reqDataArr = arr;
};

const setReqData = () => {
  if (reqDataArr.length > 2) reqDataArr = reqDataArr.slice(0, reqDataArr.length)
  for (let key in reqDataArr[0]) {
    current.value = reqDataArr[0][key] = 1;
  }
  // 深克隆，不然点击会直接改变reqDataArr
  if(window.$paramsArr){
    let dpCloneArr = [];
    // 去掉undefined
    for(let i = 0 ; i< window.$paramsArr.length ; i++){
      for(let k in window.$paramsArr[i]){
        if( k == 'undefined'){
          window.$paramsArr.splice(i,1)
          i--
        }
      }
    }
    dpCloneArr = JSON.parse(
      JSON.stringify(window.$paramsArr)
    );
    reqDataArr = reqDataArr.concat(dpCloneArr) 
  }

};

let timer = null;
const doSearch = () => {
  setReqData()
  // 防抖处理
  if (timer) clearTimeout(timer);
  timer = setTimeout(() => {
    isfrensh.value++;
     message.success('已查询到最新结果')
  }, 500);
};

const doClear = (orgArr) => {
  // orgArr 为初始值
  for (let i = 0; i < orgArr.length; i++) {
    for (let k in orgArr[i]) {
      window.$paramsArr[i][k] = orgArr[i][k]
    }
  }
};

watch(isfrensh, () => {
  getTableData(reqDataArr);
});

watch(() => props.isRefrensh, () => {
  // 模拟点击重置
  // let e = document.createEvent('MouseEvents')
  // e.initEvent('click', true, true)
  // let searchField = document.querySelectorAll('#refSearch')
  // let seachBtn = searchField[searchField.length-2]
  // seachBtn.dispatchEvent(e)
  // 再次请求数据达到刷新
  doSearch()
});

onUnmounted(()=>{window.$paramsArr = []})

// 表格数据
const total = ref(0);
const tableData = ref([]);
const loading = ref(false)

// 获取表格数据，在这里发请求
async function getTableData(arr) {
  let params = {};
  arr.forEach(item => { //过滤掉没有的元素（ps：arr这个东西会越堆越多，而且会有空对象）
    if (item) {
      const key = Object.keys(item)[0];
      params[key] = item[key];  //不能在赋值的时候判断是否为空，这样会变化更新不了╮(╯-╰)╭ 
      if (!params[key]) delete params[key];
    }
  })
  loading.value = true
  /****** 在这里更改请求方式 *******/
  const res = await props.renderTable(params);
  // if (res.meta.status !== 200) {
  //   message.error("请求失败");
  //   loading.value = false
  //   return;
  // }
  /****** 将得到的数据赋值 ********/
  loading.value = false
  tableData.value = res.data.list;
  total.value = res.data.total;
}

onMounted(() => {
  setPagedata();
  setReqData();
  isfrensh.value++;
});

// 分页逻辑
const pageSizeOptions = ref(["5", "10", "50"]);
const current = ref(1);
const pageSize = ref(5);
const onShowChange = (newNum, newSize) => {
  for (let key in reqDataArr[0]) {
    current.value = reqDataArr[0][key] = newNum;
  }
  for (let key in reqDataArr[1]) {
    pageSize.value = reqDataArr[1][key] = newSize;
  }
  isfrensh.value++;
};

// 展开收起
const flod = ref(false)
const handleFold = () => {
  flod.value = !flod.value
}
</script>
<style scoped lang="less">
@import "./tlTable.less";
</style>